package org.layuiframework.stereotype.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.layuiframework.stereotype.security.impl.LoginAttemptService;
import org.layuiframework.stereotype.vo.ResultVo;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证登录失败处理
 */
@Component
@ConditionalOnMissingBean(AuthenticationFailureHandler.class)
public class AuthenticationFailure implements AuthenticationFailureHandler {

    @Resource
    private LoginAttemptService attempt;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        ObjectMapper mapper = new ObjectMapper();
        ResultVo responseEntity = new ResultVo((Object)null);
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        String username = httpServletRequest.getParameter("username");
        String password = httpServletRequest.getParameter("password");
        responseEntity.setCode(200);
        if (e instanceof LockedException) {
            responseEntity.setMsg("账号已锁定，请" + attempt.getLockTime(username) + "后再试");
        } else {
            attempt.loginFailed(username);//记录登录失败用户名
            int num = attempt.getLockNum(username);
            responseEntity.setMsg("账号或密码错误，还剩" + num + "次尝试机会");
        }
        responseEntity.setData(null);
        response.getWriter().write(mapper.writeValueAsString(responseEntity));
    }
}
